import { flysel } from "../plugin/flysel.js";
import { Retarder } from './tool.js'

const bar_box = flysel('#scroll-bar-box')
const thumb = flysel('#scroll-thumb')
const { documentElement: html, body } = document
const curtain = flysel('#scroll-curtain')
/**初始化滚动条 */
export function init(time) {
    window.addEventListener('resize', upBar)

    const hideBar = new Retarder(() => {
        bar_box.addClass('hide')
    }, time, 100)
    const bd = {
        _isDown: false,
        get isDown() {
            return this._isDown
        },
        set isDown(v) {
            this._isDown = v
            bar_box.booleClass(v, 'hover')
            v? curtain.block() : curtain.hide()
            console.log(curtain);
        },
        devTop: 0
    }

    bar_box.on({
        mouseenter() {
            bar_box.removeClass('hide')
            hideBar.clear()
        },
        mousedown(e) {
            if (!thumb.e.isEqualNode(e.target)) {
                /**body总高度 */
                const a = body.scrollHeight
                /**body可视高度 */
                const b = html.clientHeight
                /**滑块高度 */
                const h = thumb.e.clientHeight
                bd.devTop = h / 2
                const y = e.clientY - bd.devTop
                const dev = y / (b - h) * (a - b)
                window.scrollTo(0, dev)
                bd.isDown = true
            }
        },
        mouseleave() {
            hideBar.reset()
        }
    })

    thumb.on({
        mousedown(e) {
            bd.isDown = true
            bd.devTop = e.offsetY
        },
    })

    flysel.on({
        scroll() {
            upBar()
            bar_box.removeClass('hide')
            hideBar.reset()
        },
        mousemove(e) {
            if (bd.isDown) {
                /**body总高度 */
                const a = body.scrollHeight
                /**body可视高度 */
                const b = html.clientHeight
                /**滑块高度 */
                const h = thumb.e.clientHeight
                const y = e.clientY - bd.devTop
                const dev = y / (b - h) * (a - b)
                window.scrollTo(0, dev)
            }
        },
        mouseup() {
            if (bd.isDown) {
                bd.isDown = false
            }
            hideBar.clear()
        }
    })

    bar_box.css('display', 'block')
}
/**隐藏滚动条 */
export function hideBar() {
    bar_box.addClass('hide')
}

export function upBar() {
    /**body总高度 */
    const a = body.scrollHeight
    /**body可视高度 */
    const b = html.clientHeight
    /**滚动距离 */
    const c = html.scrollTop
    const f = c / (a - b)
    const h = b ** 2 / a
    thumb.css('height', h)
    let ts = (b - h) * f
    if (ts <= 0) ts = 0
    thumb.css('transform', `translate(0, ${ts}px)`)
}